<template>
  <div class="player-info">
    <div class="page-header">
      <h3>玩家信息</h3>
      <div class="header-tip">支持通过ID/下属员号查询活跃用户</div>
    </div>

    <!-- 筛选表单 -->
    <div class="filter-section">
      <el-form :inline="true" :model="filterForm" size="small">
        <el-form-item label="uuid">
          <el-input v-model="filterForm.uid" placeholder="请输入用户ID"></el-input>
        </el-form-item>
        
        <el-form-item label="昵称">
          <el-input v-model="filterForm.nick" placeholder="请输入昵称"></el-input>
        </el-form-item>
        
        <el-form-item label="账号">
          <el-input v-model="filterForm.account" placeholder="请输入账号"></el-input>
        </el-form-item>

        <el-form-item label="用户状态">
          <el-select v-model="filterForm.status" placeholder="请选择">
            <el-option label="任意" :value="-1"></el-option>
            <el-option label="正常" :value="0"></el-option>
            <el-option label="禁用" :value="1"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="VIP等级">
          <el-select v-model="filterForm.vip" placeholder="请选择">
            <el-option label="任意" :value="-1"></el-option>
            <el-option label="VIP0" :value="0"></el-option>
            <el-option label="VIP1" :value="1"></el-option>
            <el-option label="VIP2" :value="2"></el-option>
            <el-option label="VIP3" :value="3"></el-option>
            <el-option label="VIP4" :value="4"></el-option>
            <el-option label="VIP5" :value="5"></el-option>
            <el-option label="VIP6" :value="6"></el-option>
            <el-option label="VIP7" :value="7"></el-option>
            <el-option label="VIP8" :value="8"></el-option>
            <el-option label="VIP9" :value="9"></el-option>
            <el-option label="VIP10" :value="10"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="在线状态">
          <el-select v-model="filterForm.online" placeholder="请选择">
            <el-option label="任意" :value="-1"></el-option>
            <el-option label="不在线" :value="0"></el-option>
            <el-option label="在线" :value="1"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="渠道">
          <el-select v-model="filterForm.channel" placeholder="请选择渠道" clearable>
            <el-option
              v-for="item in channelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="IP地址">
          <el-input v-model="filterForm.IP" placeholder="请输入IP地址"></el-input>
        </el-form-item>
        
        <el-form-item label="设备编号">
          <el-input v-model="filterForm.adid" placeholder="请输入设备编号"></el-input>
        </el-form-item>
        
        <el-form-item label="手机号">
          <el-input v-model="filterForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>

        <el-form-item label="注册时间">
          <el-date-picker
            v-model="filterForm.register_time_range"
            type="datetimerange"
            range-separator="至"
            start-placeholder="起始时间"
            end-placeholder="结束时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        
        <el-form-item label="靓号">
          <el-input v-model="filterForm.special_uid" placeholder="请输入靓号" type="number"></el-input>
        </el-form-item>
        
        <el-button type="primary" size="small" @click="handleSearch">筛 选</el-button>
        <el-button size="small" @click="resetFilter">重 置</el-button>
      </el-form>
      
      <div class="filter-buttons">
      
      </div>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      border
      stripe
      style="width: 100%"
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      v-loading="loading"
    
    >
      <el-table-column prop="uuid" label="uuid" width="80"></el-table-column>
      <el-table-column prop="account" label="account" width="120"></el-table-column>
      <el-table-column prop="nickname" label="昵称" width="100"></el-table-column>
      <el-table-column prop="totalRecharge" label="累计充值" width="100"></el-table-column>
      <el-table-column prop="totalWithdraw" label="累计提现" width="100"></el-table-column>
      <el-table-column prop="give" label="总赠出" width="100"></el-table-column>
      <el-table-column prop="donated" label="总受赠" width="100"></el-table-column>
      <el-table-column prop="totalWan" label="总玩" width="80"></el-table-column>
      <el-table-column prop="totalIn" label="总赢" width="80"></el-table-column>
      <el-table-column prop="goldCoins" label="金币" width="100"></el-table-column>
      <el-table-column prop="goldCoinShou" label="首充前金币" width="80"></el-table-column>
      <el-table-column prop="vip" label="vip" width="60"></el-table-column>
      <el-table-column prop="vipTime" label="vip时间" width="160"></el-table-column>
      <el-table-column prop="agentId" label="代理商等级" width="100"></el-table-column>
      <el-table-column prop="agentProfit" label="代理商累计分润奖励" width="140"></el-table-column>
      <el-table-column prop="accountStatus" label="帐号状态" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.accountStatus === '正常' ? 'success' : 'danger'">
            {{ scope.row.accountStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="mobile" label="手机号" width="180"></el-table-column>
      <el-table-column prop="emilt" label="邮箱" width="180"></el-table-column>
      <el-table-column prop="channel" label="渠道" width="80"></el-table-column>
      <el-table-column prop="registerTime" label="注册时间" width="160"></el-table-column>
      <el-table-column prop="lastLoginTime" label="最近登录时间" width="160"></el-table-column>
      <el-table-column prop="recentRechargeTime" label="最近充值时间" width="160"></el-table-column>
      <el-table-column prop="registerIp" label="注册IP" width="140"></el-table-column>
      <el-table-column prop="sameDevice" label="同设备账号数量" width="120"></el-table-column>
      <el-table-column prop="sameIp" label="同IP账号数量" width="120"></el-table-column>
      <el-table-column prop="passwordNumber" label="密码账号数量" width="80"></el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
                  <template slot-scope="scope">
            <el-button type="primary" size="mini" @click.stop="handleEdit(scope.row)" style="margin-right: 5px">编辑</el-button>
            <!-- <el-button type="info" size="mini" @click.stop="handleView(scope.row)" style="margin-right: 5px">查看</el-button> -->
            <el-button 
              :type="scope.row.accountStatus === '不正常' ? 'success' : 'danger'" 
              size="mini" 
              @click.stop="handleToggleDisable(scope.row)"
            >
              {{ scope.row.accountStatus === '不正常' ? '解禁' : '禁用' }}
            </el-button>
          </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    
    <!-- 提示信息 -->
    <div class="info-tip">
      其中：标签为2时userTags，手机输入的标签关于系统标明的标签
    </div>

    <!-- 编辑对话框 -->
    <el-dialog title="修改玩家信息" :visible.sync="dialogVisible" width="50%">
      <el-form :model="editForm" label-width="120px">
        <el-form-item label="账号密码">
          <div style="display: flex;align-items: center;">
            <el-input v-model="editForm.password" type="password"  placeholder="输入修改密码（大于七位）"></el-input>
            <el-button @click="handleChangePassword" type="primary" style="width: 100px;height: 100%;background-color: cadetblue;">修改</el-button>

          </div>
        </el-form-item>
        <el-form-item label="金币">
          <el-input v-model="editForm.amount" placeholder="请输入金币"></el-input>
        </el-form-item>
        <el-form-item label="WhatsApp">
          <el-input v-model="editForm.whatsapp" placeholder="请输入WhatsApp"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="用户渠道">
       
          <el-input v-model="editForm.userChannel" placeholder="请输入用户渠道"></el-input>
        </el-form-item>
                  <el-form-item label="标签">
            <el-select v-model="editForm.tag" placeholder="请选择">
              <el-option label="0" :value="'0'"></el-option>
              <el-option label="1" :value="'1'"></el-option>
              <el-option label="2" :value="'2'"></el-option>
              <el-option label="3" :value="'3'"></el-option>
              <el-option label="4" :value="'4'"></el-option>
              <el-option label="5" :value="'5'"></el-option>
              <el-option label="6" :value="'6'"></el-option>
              <el-option label="-1" :value="'-1'"></el-option>
            </el-select>
          </el-form-item>
        <el-form-item>
          <el-checkbox v-model="editForm.support">关闭赠送</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="editForm.noSendPromotions">不参与金币排行</el-checkbox>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="savePlayerInfo">保存修改</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { playerList,playerForbid,playerResetPasswd,updatePlayer } from '@/api/user'
import channelMixin from '@/mixins/channelMixin'

export default {
  name: 'PlayerInfo',
  mixins: [channelMixin],
  data() {
    return {
      filterForm: {
        uid: '',
        nick: '',
        account: '',
        status: -1,
        vip: -1,
        online: -1,
        channel: null,
        IP: '',
        adid: '',
        phone: '',
        register_time_range: [],
        special_uid: ''
      },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      dialogVisible: false,
      editForm: {
        password: '',
        uuid: '',
        account: '',
        amount: '',
        whatsapp: '',
        email: '',
        userChannel: '',
        tag: '0',
        support: false,  // donate: 0表示允许赠送，1表示不允许赠送
        noSendPromotions: false  // join_rank: 1表示参与排行，0表示不参与排行
      }
    }
  },
  methods: {
    // 点击修改密码
    async handleChangePassword(){ 
      if(this.editForm.password.length<7){
        this.$message.error('密码长度不能小于七位')
        return
      }
      let n=await playerResetPasswd({'uid':this.editForm.uuid,'passwd':this.editForm.password})
      if(n.code==0){
        this.$message.success('修改成功')
      }else{
        this.$message.error(n.message)
      }
    },
    handleSearch() {
      this.currentPage = 1
      // 筛选参数转换为API所需格式
      const apiFilterParams = {}
      
      // 遍历过滤对象，只传递有值的参数
      Object.keys(this.filterForm).forEach(key => {
        const value = this.filterForm[key];
        
        // 跳过空值，但-1是有效值
        if (value === '' || value === undefined || value === null) {
          return;
        }
        
        // 处理注册时间范围
        if (key === 'register_time_range' && Array.isArray(value) && value.length === 2) {
          apiFilterParams.register_begin_time = value[0];
          apiFilterParams.register_end_time = value[1];
          return;
        }
        
        // 处理渠道参数
        if (key === 'channel') {
          apiFilterParams[key] = this.formatChannelParam(value);
          return;
        }
        
        // 数字类型字段
        if (['uid', 'status', 'vip', 'online', 'special_uid'].includes(key)) {
          if (value !== '') {
            apiFilterParams[key] = Number(value);
          }
        } else {
          apiFilterParams[key] = value;
        }
      })
      
      this.fetchData(apiFilterParams)
    },
          resetFilter() {
        this.filterForm = {
          uid: '',
          nick: '',
          account: '',
          status: -1,
          vip: -1,
          online: -1,
          channel: null,
          IP: '',
          adid: '',
          phone: '',
          register_time_range: [],
          special_uid: ''
        }
      this.currentPage = 1
     this.handleSearch()
    },
    handleSizeChange(val) {
      this.pageSize = val
   this.handleSearch()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.handleSearch()
    },
    async fetchData(filterParams = {}) {
      this.loading = true
      try {
        const res = await playerList({
          page: this.currentPage,
          page_size: this.pageSize,
          ...filterParams
        })
        
        console.log('API response:', res);
        if (res && res.data) {
          // Adjust based on actual response structure
          const players = Array.isArray(res.data) ? res.data : (res.data.players || []);
                     this.tableData = players.map(player => {
            return {
              uuid: player.uid || '',
              account: player.account || '',
              nickname: player.nick || '',
              totalRecharge: player.total_recharge || 0,
              totalWithdraw: player.total_cash || 0,
              give: player.total_donate || 0,
              donated: player.total_be_donate || 0,
              totalWan: player.total_player || 0,
              totalIn: player.total_win || 0,
              goldCoins: player.coin || 0,
              goldCoinShou: player.before_recharge_coin || 0,
              vip: player.vip || 0,
              vipTime: player.vip_time || '',
              agentId: player.agent_level || 0,
              agentProfit: player.agent_total_reward || 0,
              accountStatus: player.status == 0 ? '正常' : '不正常',
              mobile: player.phone || '',
              emilt: player.mail || '',
              channel: player.channel || '',
              registerTime: player.register_time || '',
              lastLoginTime: player.login_time || '',
              recentRechargeTime: player.recharge_time || '',
              registerIp: player.register_ip || '',
              sameDevice: player.same_device_account_count || 0,
              sameIp: player.same_ip_account_count || 0,
              passwordNumber: player.same_passwd_account_count || 0
            }
          });
          
          // Handle pagination data
          if (res.data.total_page !== undefined) {
            this.total = res.data.total_page * this.pageSize
          } else if (res.total_page !== undefined) {
            this.total = res.total_page * this.pageSize
          } else if (res.data.total !== undefined) {
            this.total = res.data.total
          }
          
          this.currentPage = res.data.page || res.page || 1
        }
      } catch (error) {
        console.error('获取玩家信息列表失败:', error)
      } finally {
        this.loading = false
      }
    },
    handleRowClick(row) {
      this.handleEdit(row)
    },
    handleEdit(row) {
      console.log('Editing row:', row);
      this.editForm = {
        password: '',
        uuid: row.uuid,
        account: row.account,
        amount: row.goldCoins || '0',
        whatsapp: '',
        email: row.emilt || '',
        userChannel: row.channel || '0',
        tag: (typeof row.tag !== 'undefined' && row.tag !== null) ? String(row.tag) : '0',
        support: false,  // 默认允许赠送
        noSendPromotions: false  // 默认参与排行
      };
      this.dialogVisible = true;
    },
    handleView(row) {
      this.$message.info(`查看玩家信息: ${row.account}`)
    },
    handleToggleDisable(row) {
      // 根据当前状态决定是禁用还是解禁
      const isCurrentlyDisabled = row.accountStatus === '不正常';
      const forbidValue = isCurrentlyDisabled ? 0 : 1;
      const actionName = isCurrentlyDisabled ? '解禁' : '禁用';
      
      this.$confirm(`确认${actionName}该玩家账号吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.loading = true;
        try {
          const result = await playerForbid({"uid": row.uuid, "forbid": forbidValue});
          
          if (result && result.code == 0) {
            this.$message.success(`${actionName}成功`);
            // 刷新列表数据
            this.handleSearch();
          } else {
            this.$message.error(result.message || `${actionName}失败`);
          }
        } catch (error) {
          console.error(`${actionName}操作失败:`, error);
          this.$message.error(`${actionName}操作失败`);
        } finally {
          this.loading = false;
        }
      }).catch(() => {
        this.$message.info('已取消操作');
      });
    },
    
    // 保留旧方法以保持兼容性
    handleDelete(row) {
      this.handleToggleDisable(row);
    },
    async savePlayerInfo() {
      this.loading = true;
      
      try {
        // 准备参数
        const params = {
          uid: parseInt(this.editForm.uuid) || 0,
          coin: parseInt(this.editForm.amount) || 0,
          whatsapp: this.editForm.whatsapp||'' ,
          // whatsapp: parseInt(this.editForm.whatsapp) || 0,
          mail: this.editForm.email || '',
          channel: parseInt(this.editForm.userChannel) || 0,
          tag: parseInt(this.editForm.tag) || 0,
          donate: this.editForm.support ? 1 : 0,
          join_rank: this.editForm.noSendPromotions ? 1 : 0
        };
        
        console.log('提交参数:', params);
        
        const result = await updatePlayer(params);
        
        if (result && result.code == 0) {
          this.dialogVisible = false;
          this.$message.success('保存成功');
          
          // 刷新列表数据
          this.handleSearch();
        } else {
          this.$message.error(result.message || '保存失败');
        }
      } catch (error) {
        console.error('保存失败:', error);
        this.$message.error('保存操作失败');
      } finally {
        this.loading = false;
      }
    }
  },
  mounted() {
    const apiFilterParams = {}
      
    // 遍历过滤对象，只传递有值的参数
    Object.keys(this.filterForm).forEach(key => {
      const value = this.filterForm[key];
      
      // 跳过空值
      if (value === '' || value === undefined || value === null) {
        return;
      }
      
      // 处理渠道参数
      if (key === 'channel') {
        apiFilterParams[key] = this.formatChannelParam(value);
        return;
      }
      
      // status和vip需要作为数字传递
      if (key === 'status') {
        // 确保status作为数字传递，并且当值为-1时，也要传递
        apiFilterParams[key] = Number(value);
      } else if (key === 'vip' && value !== '') {
        apiFilterParams[key] = Number(value);
      } else {
        apiFilterParams[key] = value;
      }
    })
    this.fetchData(apiFilterParams)
  }
}
</script>

<style scoped>
.player-info {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-tip {
  font-size: 14px;
  color: #606266;
  margin-top: 5px;
}

.filter-section {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.filter-buttons {
  margin-top: 10px;
  display: flex;
  justify-content: flex-start;
}

.filter-buttons .el-button {
  width: 80px;
  margin-right: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.info-tip {
  margin-top: 20px;
  font-size: 14px;
  color: #909399;
}
</style> 